﻿<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>table 组件综合演示 - Layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="//unpkg.com/layui@2.10.1/dist/css/layui.css" rel="stylesheet">
</head>

<body>
    <div style="padding: 16px;">
        <!-- 添加查询条件 -->
        <div style="margin-bottom: 10px;">
            <input type="text" id="menuNameSearch" placeholder="请输入菜单名称" class="layui-input" style="width: 200px; display: inline-block;">
            <button class="layui-btn" id="searchBtn">查询</button>
        </div>
        <!-- 添加添加权限按钮 -->
        <button class="layui-btn" id="addPermissionBtn">添加权限</button>
        <table class="layui-hide" id="test" lay-filter="test"></table>
    </div>
    <!-- 新增的最后一列操作按钮模板 -->
    <script type="text/html" id="operateTemplate">
        <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete">删除</a>
        <a class="layui-btn layui-btn-xs" lay-event="update">修改</a>
    </script>

    <!-- 修改表单模板 -->
    <script type="text/html" id="updateFormTemplate">
        <form class="layui-form" lay-filter="updateForm">
            <!-- 新增隐藏字段存储 menuId -->
            <input type="hidden" name="menuId" id="menuId">
            <div class="layui-row">
                <div class="layui-col-md-6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">菜单名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="menuName" lay-verify="required" placeholder="请输入菜单名称" class="layui-input">
                        </div>
                    </div>
                </div>
                <div class="layui-col-md-6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">地址</label>
                        <div class="layui-input-block">
                            <input type="text" name="url" lay-verify="required" placeholder="请输入地址" class="layui-input">
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-row">
                <div class="layui-col-md-6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">父级菜单</label>
                        <div class="layui-input-block">
                            <select name="pId" lay-search id="parentMenuSelectUpdate">
                                <option value="">请选择父级菜单</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="layui-col-md-6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">修改人</label>
                        <div class="layui-input-block">
                            <input type="text" name="updateName" lay-verify="required" placeholder="请输入修改人" class="layui-input">
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit lay-filter="submitUpdateForm">提交修改</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>
    </script>

    <!-- 添加权限表单模板 -->
    <script type="text/html" id="addPermissionTemplate">
        <form class="layui-form" id="permissionForm" style="width: 350px">
            <div class="layui-row">
                <div class="layui-col-md-6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">权限名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="menuName" required lay-verify="required" placeholder="请输入权限名称" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                </div>
                <div class="layui-col-md-6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">URL 地址</label>
                        <div class="layui-input-block">
                            <input type="text" name="url" required lay-verify="required" placeholder="请输入 URL 地址" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-row">
                <div class="layui-col-md-6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">父级菜单</label>
                        <div class="layui-input-block">
                            <select name="pId" lay-search id="parentMenuSelect">
                                <option value="">请选择父级菜单</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="layui-col-md-6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">创建人</label>
                        <div class="layui-input-block">
                            <input type="text" name="createName" required lay-verify="required" placeholder="请输入创建人" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit lay-filter="addPermission">立即提交</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>
    </script>

    <script src="//unpkg.com/layui@2.10.1/dist/layui.js"></script>
    <script>
        layui.use(['table', 'dropdown', 'layer', 'form', 'jquery'], function () {
            var table = layui.table;
            var dropdown = layui.dropdown;
            var layer = layui.layer;
            var form = layui.form;
            var $ = layui.jquery;

            // 表格渲染配置
            table.render({
                elem: '#test',
                url: 'https://localhost:7174/api/Message/GetMenu', // 后端数据接口
                //url: "@ViewBag.BaseUrl/T5/Message/GetMenu",
                toolbar: '#toolbarDemo',
                defaultToolbar: ['filter', 'exports', 'print', {
                    title: '提示',
                    layEvent: 'LAYTABLE_TIPS',
                    icon: 'layui-icon-tips',
                    onClick: function () {
                        layer.alert('自定义工具栏图标按钮');
                    }
                }],
                height: 'full-35',
                css: ['.layui-table-tool-temp{padding-right: 145px;}'].join(''),
                cellMinWidth: 80,
                totalRow: true,
                page: true,
                cols: [[
                    { type: 'checkbox', fixed: 'left' },
                    { field: 'menuId', fixed: 'left', title: 'ID', sort: true, totalRow: '合计：' },
                    { field: 'menuName', title: '菜单名称' },
                    { field: 'url', title: '地址' },
                    { field: 'parendName', title: '父级菜单' },
                    { field: 'createName', title: '创建人' },
                    { field: 'createTime', title: '创建时间' },
                    { field: 'updateName', title: '修改人' },
                    { field: 'updateTime', title: '修改时间' },
                    { title: '操作', toolbar: '#operateTemplate', width: 150 }
                ]],
                error: function (res, msg) {
                    console.error('表格加载失败:', res, msg);
                }
            });

            // 监听查询按钮点击事件
            $('#searchBtn').on('click', function () {
                var menuName = $('#menuNameSearch').val();
                table.reload('test', {
                    where: {
                        menuName: menuName
                    },
                    page: {
                        curr: 1 // 重新从第一页开始
                    }
                });
            });

            // 监听行工具事件
            table.on('tool(test)', function (obj) {
                var data = obj.data;
                if (obj.event === 'delete') {
                    layer.confirm('确定要删除这条记录吗？', function (index) {
                        $.ajax({
                            url: 'https://localhost:7272/api/Message/DelMenu',
                            //url: "@ViewBag.BaseUrl/T6/Message/DelMenu",
                            type: 'delete',
                            // 将请求数据序列化为 JSON 字符串
                            data: JSON.stringify({ menuId: data.menuId }),
                            // 设置请求头，告知服务器请求数据的格式为 JSON
                            contentType: 'application/json',
                            success: function (res) {
                                if (res.code === 204) { // 根据实际的成功状态码修改
                                    layer.close(index);
                                    layer.msg('删除成功', { icon: 1 });
                                    // 刷新表格
                                    table.reload('test');
                                } else {
                                    layer.close(index);
                                    layer.msg('删除失败: ' + res.message, { icon: 2 });
                                }
                            },
                            error: function (xhr) {
                                layer.close(index);
                                layer.msg('网络请求失败: ' + xhr.status, { icon: 2 });
                                console.error('AJAX 请求失败:', xhr.responseText);
                            }
                        });
                    });
                } else if (obj.event === 'update') {
                    // 打开修改弹窗
                    layer.open({
                        type: 1,
                        title: '修改菜单信息',
                        content: $('#updateFormTemplate').html(),
                        area: ['600px', '600px'],
                        success: function (layero, index) {
                            // 填充表单数据
                            form.val('updateForm', data);
                            // 设置隐藏字段的值
                            layero.find('#menuId').val(data.menuId);
                            // 获取父级菜单数据并填充下拉框
                            $.ajax({
                                url: 'https://localhost:7174/api/Message/GetMenuAll',
                                //url: "@ViewBag.BaseUrl/T5/Message/GetMenuAll",
                                type: 'GET',
                                contentType: 'application/json',
                                success: function (res) {
                                    if (res.code === 0) {
                                        var options = '';
                                        // 遍历后端返回数据
                                        $.each(res.data, function (index, item) {
                                            options += '<option value="' + item.menuId + '">' + item.menuName + '</option>';
                                        });
                                        // 添加到下拉框
                                        layero.find('#parentMenuSelectUpdate').append(options);
                                        // 渲染下拉框
                                        form.render('select');
                                        // 反填父级菜单
                                        layero.find('#parentMenuSelectUpdate').val(data.pId);
                                        form.render('select');
                                    } else {
                                        layer.msg('获取数据失败：' + res.msg);
                                    }
                                },
                                error: function (xhr, status, error) {
                                    layer.msg('网络请求失败，请检查网络！');
                                    console.error(error);
                                }
                            });
                            // 获取 localStorage 中的昵称
                            var nickName = localStorage.getItem('nickName');
                            if (nickName) {
                                layero.find('input[name="updateName"]').val(nickName);
                            }
                        },
                        yes: function (index, layero) {
                            // 模拟提交表单
                            layero.find('form').find('button[lay-filter="submitUpdateForm"]').click();
                        }
                    });
                }
            });

            // 监听表单提交事件
            form.on('submit(submitUpdateForm)', function (data) {
                var formData = data.field;

                $.ajax({
                    url: 'https://localhost:7272/api/Message/UpdateMenu',
                    //url: "@ViewBag.BaseUrl/T6/Message/UpdateMenu",
                    type: 'PUT',
                    data: JSON.stringify(formData),
                    contentType: 'application/json',
                    success: function (res) {
                        if (res.code === 206) {
                            layer.msg('修改成功', { icon: 1 });
                            layer.closeAll(); // 关闭所有弹窗
                            table.reload('test'); // 刷新表格
                        } else {
                            layer.msg('修改失败: ' + res.message, { icon: 2 });
                        }
                    },
                    error: function (xhr) {
                        layer.msg('网络请求失败: ' + xhr.status, { icon: 2 });
                        console.error('AJAX 请求失败:', xhr.responseText);
                    }
                });

                return false; // 阻止表单默认提交
            });

            // 监听添加权限按钮点击事件
            $('#addPermissionBtn').on('click', function () {
                layer.open({
                    type: 1,
                    title: '添加权限',
                    content: $('#addPermissionTemplate').html(),
                    area: ['400px', '500px'],
                    success: function () {
                        // 获取父级菜单数据并填充下拉框
                        $.ajax({
                            url: 'https://localhost:7174/api/Message/GetMenuAll',
                            //url: "@ViewBag.BaseUrl/T5/Message/GetMenuAll",
                            type: 'GET',
                            contentType: 'application/json',
                            success: function (res) {
                                if (res.code === 0) {
                                    var options = '';
                                    // 遍历后端返回数据
                                    $.each(res.data, function (index, item) {
                                        options += '<option value="' + item.menuId + '">' + item.menuName + '</option>';
                                    });
                                    // 添加到下拉框
                                    $('#parentMenuSelect').append(options);
                                    // 渲染下拉框
                                    form.render('select');
                                } else {
                                    layer.msg('获取数据失败：' + res.msg);
                                }
                            },
                            error: function (xhr, status, error) {
                                layer.msg('网络请求失败，请检查网络！');
                                console.error(error);
                            }
                        });
                    }
                });
            });

            // 监听添加权限表单提交事件
            form.on('submit(addPermission)', function (data) {
                // 发送 Ajax 请求
                $.ajax({
                    url: 'https://localhost:7272/api/Message/AddMenu',
                    //url: "@ViewBag.BaseUrl/T6/Message/AddMenu",
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(data.field),
                    dataType: 'json',
                    success: function (res) {
                        if (res.code === 212) {
                            layer.msg('添加成功');
                            $('#permissionForm')[0].reset();
                            layer.closeAll();
                            table.reload('test');
                        } else {
                            layer.msg(res.msg);
                        }
                    },
                    error: function () {
                        layer.msg('请求出错，请稍后重试');
                    }
                });
                return false;
            });
        });
    </script>
</body>

</html>